package cn.bitkit.base.container;

import cn.bitkit.base.constants.BasicApiCode;
import cn.bitkit.base.exception.BusinessAssert;
import cn.bitkit.base.exception.BusinessException;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * 
 * @author changbo
 * 
 */
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class ApiResponse<T> {

	/** 返回码: 默认成功  **/
	private int code = BasicApiCode.SUCCESS.code;
	/** 返回信息  **/
	private String msg = null;
	/** 追踪号  **/
	private String trace;
	/** 返回数据  **/
	private T data = null;

    public static <T> ApiResponse<T> fail(String msg){
    	return fail(BasicApiCode.FAIL.code, msg);
    }
    
    public static <T> ApiResponse<T> fail(int code, String msg){
    	return new ApiResponse<T>(code, msg, null, null);
    }
    
    public static <T> ApiResponse<T> fail(BusinessException e){
    	return fail(e.getErrorCode(), e.getErrorMsg());
    }
    
    public static <T> ApiResponse<T> success(){
    	return success(null);
    }
    
    public static <T> ApiResponse<T> success(T data){
    	return new ApiResponse<T>(BasicApiCode.SUCCESS.code, null, null, data);
    }
	
	public static boolean isSuccess(ApiResponse<?> resp) {
		return resp != null && BasicApiCode.SUCCESS.code == resp.getCode();
	}

	public static boolean isFail(ApiResponse<?> resp) {
		return !isSuccess(resp);
	}


	public ApiResponse<T> assertSuccess() {
		BusinessAssert.isTrue(isSuccess(this), msg);
		return this;
	}
	
}
